/*
 * SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

use std::fs::File;
use std::io::Write;
use std::process::Command;
use tempfile::tempdir;

#[test]
fn test_add_and_list() {
    let dir = tempdir().unwrap();
    let zip_path = dir.path().join("test.zip");
    let file_path = dir.path().join("file1.txt");
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "hello world").unwrap();

    // 添加文件到zip
    let status = Command::new("./target/debug/utzip")
        .arg(&zip_path)
        .arg(&file_path)
        .status()
        .unwrap();
    assert!(status.success());

    // 使用unzip -l 检查内容
    let output = Command::new("unzip")
        .arg("-l")
        .arg(&zip_path)
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("file1.txt"));
}

#[test]
fn test_update_and_freshen() {
    let dir = tempdir().unwrap();
    let zip_path = dir.path().join("test.zip");
    let file_path = dir.path().join("file2.txt");
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "v1").unwrap();

    // 添加
    Command::new("./target/debug/utzip")
        .arg(&zip_path)
        .arg(&file_path)
        .status()
        .unwrap();

    // 修改文件
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "v2").unwrap();

    // update
    Command::new("./target/debug/utzip")
        .arg("-u")
        .arg(&zip_path)
        .arg(&file_path)
        .status()
        .unwrap();

    // freshen
    Command::new("./target/debug/utzip")
        .arg("-f")
        .arg(&zip_path)
        .status()
        .unwrap();
}

#[test]
fn test_delete() {
    let dir = tempdir().unwrap();
    let zip_path = dir.path().join("test.zip");
    let file_path = dir.path().join("file3.txt");
    let entry_name = file_path.to_str().unwrap().trim_start_matches('/');

    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "delete me").unwrap();

    // 添加
    Command::new("./target/debug/utzip")
        .arg(&zip_path)
        .arg(&file_path)
        .status()
        .unwrap();

    // 删除
    Command::new("./target/debug/utzip")
        .arg(&zip_path)
        .arg("-d")
        .arg(entry_name)
        .status()
        .unwrap();

    // 检查已删除
    let output = Command::new("unzip")
        .arg("-l")
        .arg(&zip_path)
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.contains("file3.txt"));
}
